<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="12">
          <a-col :md="4" :sm="4">
            <a-form-item label="月租编号">
              <a-input placeholder="请输入月租编号" v-model="queryParam.monthlyCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="4">
            <a-form-item label="车主姓名">
              <a-input placeholder="车主姓名" v-model="queryParam.carOwnerName"></a-input>
            </a-form-item>
          </a-col>

          <a-col :md="4" :sm="4">
            <a-form-item label="车牌号">
              <a-input placeholder="车牌号" v-model="queryParam.plateNo"></a-input>
            </a-form-item>
          </a-col>

          <a-col :md="4" :sm="4">
            <a-form-item label="到期时间：">
              <a-date-picker placeholder="开始日期" @change="onChangeStartTime" />
            </a-form-item>
          </a-col>
          <a-col :md="3" :sm="3">
            <a-form-item label="至：">
              <a-date-picker placeholder="结束日期" @change="onChangeEndTime" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="12">
          <a-col :md="4" :sm="8">
            <a-form-item label="月租套餐">
              <a-select
                placeholder="请选择月租套餐"
                v-model="queryParam.packageId"
                :options="monthlyPackageInfoList"
              >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="4">
            <a-form-item label="车位号">
              <a-input placeholder="车位号" v-model="queryParam.parkNumber"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="通行权限">
              <a-select
                placeholder="请选择通行权限"
                v-model="queryParam.throughAuthorityId"
                :options="permissionGroupList"
              >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="部门/组织">
              <a-tree-select
                v-model="queryParam.monthlyDepartmentId"
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="departTree"
                placeholder="请选择部门/组织"
                tree-default-expand-all
              >
                <span slot="title" slot-scope="{ key, value }" style="color: #08c"> Child Node1{{ value }} </span>
              </a-tree-select>
            </a-form-item>
          </a-col>

          <a-col :md="4" :sm="8">
            <a-form-item label="手机号">
              <a-input placeholder="手机号" v-model="queryParam.telephone"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus" v-has="'monthinfo:add'">新增</a-button>
      <a-button
        type="primary"
        icon="download"
        style="margin-left:10px"
        @click="handleExportXls('月卡信息表')"
        v-has="'monthinfo:export'"
        >导出</a-button
      >
      <!--      <a-dropdown v-if="selectedRowKeys.length > 0">-->
      <!--        <a-menu slot="overlay">-->
      <!--          <a-menu-item key="1" @click="batchDel">-->
      <!--            <a-icon type="delete" />-->
      <!--            删除-->
      <!--          </a-menu-item>-->
      <!--        </a-menu>-->
      <!--        <a-button style="margin-left: 8px">-->
      <!--          批量操作-->
      <!--          <a-icon type="down" />-->
      <!--        </a-button>-->
      <!--      </a-dropdown>-->
    </div>

    <!-- table区域-begin -->
    <div>
      <!--      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">-->
      <!--        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择-->
      <!--        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a-->
      <!--        >项-->
      <!--        <a style="margin-left: 24px" @click="onClearSelected">清空</a>-->
      <!--      </div>-->

      <a-table
        class="AStockOutDetailTable"
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <!--  :scroll="{ x: 1800 }"      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"-->
        <span slot="action" slot-scope="text, record">
          <a-row style="width: 100%">
            <a-col :span="12" align="center">
              <a @click="handleEdit(record)"  v-has="'monthinfo:edit'"
              >修改</a>
            </a-col>
            <a-col :span="12" align="center">
              <a @click="postponeModal(record, '延期')" v-has="'monthinfo:delay'">延期</a>
            </a-col>
          </a-row>
          <a-row style="width: 100%">
            <a-col :span="12" align="center">
              <a @click="handleDetail(record)">详情</a>
            </a-col>
            <a-col :span="12" align="center">
              <!--              <a-popconfirm title="确定注销吗?" @confirm="() => postponeModal(record, '注销')">-->
              <!--                <a style="color: #1890ff">注销</a>-->
              <!--              </a-popconfirm>-->
              <a style="color: #ff4848" @click="postponeModal(record, '注销')" v-has="'monthinfo:out'">注销</a>
            </a-col>
          </a-row>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <monthlyCardInfo-modal ref="modalForm" @ok="modalFormOk"></monthlyCardInfo-modal>
    <monthlyCardInfo-modal-detail ref="detailModalForm"></monthlyCardInfo-modal-detail>
    <monthlyCar-postpone-modal ref="postponeModalForm" @ok="modalFormOk"></monthlyCar-postpone-modal>
  </a-card>
</template>

<script>
import MonthlyCardInfoModal from './modules/MonthlyCardInfoModal'
import MonthlyCardInfoModalDetail from './modules/MonthlyCardInfoModalDetail'
import MonthlyCarPostponeModal from './modules/MonthlyCarPostponeModal'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { deleteAction, downFile, getAction, postAction } from '@/api/manage'
import { filterObj } from '@/utils/util'
// import parkInfoList from '@/components/parkInfoList'
import { getMonthlyParkInfoList } from '@api/api'
import moment from 'moment'
import ListParkNumberPopover from '@views/parking/parkmonthly/components/ListParkNumberPopover'

export default {
  name: 'MonthlyCardInfoList',
  mixins: [JeecgListMixin],

  components: {
    ListParkNumberPopover,
    MonthlyCardInfoModal,
    // parkInfoList,
    MonthlyCardInfoModalDetail,
    MonthlyCarPostponeModal,
  },

  data() {
    return {
      description: '月卡信息表管理页面',
      selectedMonthlyCardId: '',
      departTree: [],
      value: undefined,
      // 表头
      columns: [
        {
          title: '车场名称',
          align: 'center',
          // width: 120,
          dataIndex: 'parkName',
        },
        {
          title: '月租编号',
          align: 'center',
          // width: 120,
          dataIndex: 'monthlyCode',
        },
        {
          title: '车主姓名',
          align: 'center',
          // width: 80,
          dataIndex: 'carOwnerName',
        },
        {
          title: '部门/组织',
          align: 'center',
          // width: 120,
          dataIndex: 'monthlyDepartmentName',
        },
        {
          title: '月租套餐',
          align: 'center',
          // width: 120,
          dataIndex: 'packageName',
        },
        {
          title: '车位号',
          align: 'center',
          // width: 100,
          dataIndex: 'parkNumber',
          customRender: function (t, r, index) {
            if (t === null || t === undefined || t === '') {
              return '无'
            }
            var array = t.split(',')
            if (array.length > 3) {
              let str = array[0] + ',' + array[1] + ',' + array[2]
              let moreInfo = ''
              for (let i = 0; i < array.length; i++) {
                moreInfo = moreInfo + array[i]
                if (i + 1 !== 0 && (i + 1) % 4 === 0) {
                  moreInfo = moreInfo + '\n'
                }
              }
              return (
                <list-park-number-popover
                  placement="bottom"
                  detail={array}
                  title="绑定车位信息"
                  simpleInfo={str}
                  trigger="click"
                  content="更多"
                />
              )
            }
            return t
          },
        },
        {
          title: '车牌号',
          align: 'center',
          // width: 150,
          dataIndex: 'plateNo',
          customRender: function (t, r, index) {
            if (t === null || t === undefined || t === '') {
              return '无'
            }
            var array = t.split(',')
            if (array.length > 3) {
              let str = array[0] + ',' + array[1] + ',' + array[2]
              let moreInfo = ''
              for (let i = 0; i < array.length; i++) {
                moreInfo = moreInfo + array[i]
                if (i + 1 !== 0 && (i + 1) % 4 === 0) {
                  moreInfo = moreInfo + '\n'
                }
              }
              return (
                <list-park-number-popover
                  placement="bottom"
                  detail={array}
                  title="绑定车牌号信息"
                  simpleInfo={str}
                  trigger="click"
                  content="更多"
                />
              )
            }
            return t
          },
        },
        {
          title: '通行权限组',
          align: 'center',
          // width: 120,
          dataIndex: 'throughAuthorityName',
        },
        {
          title: '手机号',
          align: 'center',
          // width: 120,
          dataIndex: 'telephone',
        },

        {
          title: '起始时间',
          align: 'center',
          // width: 150,
          dataIndex: 'beginTime',
          customRender: function (t, r, index) {
            let date = moment(t)
            return date.format('YYYY-MM-DD ')
          },
        },
        {
          title: '到期时间',
          align: 'center',
          dataIndex: 'endTime',
          customRender: function (t, r, index) {
            let date = moment(t)
            let isLay = r.isLay;
            if(isLay==="0"||isLay===0){
              return <span style="color:red"> {date.format('YYYY-MM-DD')} </span>;
            }
            if(isLay==="1"||isLay===1){
              return <span style="color:orange"> {date.format('YYYY-MM-DD')} </span>;
            }
            return date.format('YYYY-MM-DD')
          },
        },
        {
          title: '操作',
          dataIndex: 'action',
          // width: 150,
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/monthlyCardInfo/list',
        delete: '/monthlyCardInfo/delete',
        deleteBatch: '/monthlyCardInfo/deleteBatch',
        exportXlsUrl: 'monthlyCardInfo/exportXls',
        importExcelUrl: 'monthlyCardInfo/importExcel',
        getPermissionGroupList: '/permissionGroup/getPermissionGroup',
        getDepartmentList: '/monthlyDepartment/queryTreeList',
        getMonthlyPackageList: '/monthlyPackageInfo/getMonthlyPackageInfoList',
        getById: '/monthlyCardInfo/queryById',
      },
      queryParam: {
        monthlyCode: '',
        createTime_begin: '',
        createTime_end: '',
        type: '-1',
      },
      isorter: {
        column: 'monthly_card_info.createTime',
        order: 'desc',
      },
      monthlyPackageInfoList: [{ label: '请选择月租套餐', value: '' }],
      permissionGroupList: [{label:"请选择通行权限",value:''}],

      parkCodeList: [{ label: '请选择车场', value: '' }],
      dataClasses:['dataOrange','dataRed']
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  created() {
    this.keyupEnter()
    //this.initParkInfo()
    this.parkInfoListChange();
  },
  methods: {


    initMonthlyPackageInfoList() {
      const that = this
      getAction(this.url.getMonthlyPackageList).then((res) => {
        if (res.success) {
          that.monthlyPackageInfoList = [{ label: '请选择月租套餐', value: '' }]
          if (res.result) {
            res.result.forEach((packageInfo) => {
              that.monthlyPackageInfoList.push({
                value: packageInfo.id,
                label: packageInfo.packageName,
              })
            })
          }
        }
      })
    },

    postponeModal(record, type) {
      this.$refs.postponeModalForm.edit(record)
      this.$refs.postponeModalForm.title = `${record.parkName}-${type}月卡`
      this.$refs.postponeModalForm.explain = type == '延期' ? '需判断场内，过期后延期情况?' : '注销需判断场内车情况！'
      this.$refs.postponeModalForm.type = type == '延期' ? 1 : 2
    },
    handleAdd: function () {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
    },
    handleDetail: function (record) {
      // getAction(this.url.getById, { id: record }).then((res) => {
        this.$refs.detailModalForm.edit(record)
        this.$refs.detailModalForm.title = '详情'
        this.$refs.detailModalForm.disableSubmit = true
      // })
    },

    loadPermissionGroupList() {
      const that = this
      getAction(this.url.getPermissionGroupList).then((res) => {
        if (res.success) {
          that.permissionGroupList = [{label:"请选择通行权限",value:''}]
          res.result.forEach((permissionGroup) => {
            that.permissionGroupList.push({
              label: permissionGroup.permissionName,
              value: permissionGroup.id,
            })
          })
        }
      })
    },
    parkInfoListChange() {
      let params = Object.assign(this.queryParam, {})
      this.queryParam = {
        monthlyCode: params.monthlyCode,
        carOwnerName: params.carOwnerName,
        plateNo: params.plateNo,
        parkNumber: params.parkNumber,
      }
      this.monthlyPackageInfoList = [{ label: '请选择月租套餐', value: '' }]
      this.permissionGroupList = [{label:"请选择通行权限",value:''}]
      this.departTree = []
      this.loadDepartmentTreeList()
      this.loadPermissionGroupList()
      this.initMonthlyPackageInfoList()
    },

    loadDepartmentTreeList() {
      postAction(this.url.getDepartmentList).then((res) => {
        if (res.success) {
          this.departTree = res.result
        }
      })
    },

    handleExportXls(fileName) {
      let startTime = this.queryParam.createTime_begin
      let endTime = this.queryParam.createTime_end
      let opDesc = this.queryParam.opDesc
      let dayTime = startTime
      if (startTime == '') {
        this.$message.error('请选择导出开始日期')
        return
      }
      if (endTime == '') {
        this.$message.error('请选择导出结束日期')
        return
      }
      if (startTime != '' && endTime != '') {
        if (startTime != endTime) {
          this.$message.error('仅支持1天数据导出,请选择导出日期')
          return
        }
      }

      if (startTime == '' && endTime != '') {
        this.$message.error('请选择开始时间')
        return
      }

      if (startTime != '' && endTime == '') {
        this.$message.error('请选择结束时间')
        return
      }

      this.queryParam.dayTime = dayTime
      fileName = dayTime + fileName
      let param = { ...this.queryParam }
      if (this.queryParam.createTime_begin != '' && this.queryParam.createTime_end != '') {
        param.createTime_begin = this.queryParam.createTime_begin + ' 00:00:00'
        param.createTime_end = this.queryParam.createTime_end + ' 23:59:59'
      }

      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },

    onChangeStartTime(date, dateString) {
      this.queryParam.createTime_begin = dateString
    },

    onChangeEndTime(date, dateString) {
      this.queryParam.createTime_end = dateString
    },

    searchQuery() {
      let startTime = this.queryParam.createTime_begin
      let endTime = this.queryParam.createTime_end

      if (startTime != '' && endTime != '') {
        if (startTime > endTime) {
          this.$message.error('开始时间不能大于结束时间')
          return
        }
      }

      if (startTime == '' && endTime != '') {
        this.$message.error('请选择开始时间')
        return
      }

      if (startTime != '' && endTime == '') {
        this.$message.error('请选择结束时间')
        return
      }

      this.loadData(1)
    },

    getQueryParams() {
      var param = Object.assign({}, this.isorter, this.queryParam)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      if (!this.isEmpty(this.queryParam.createTime_begin) && !this.isEmpty(this.queryParam.createTime_end)) {
        param.createTime_begin = this.queryParam.createTime_begin + ' 00:00:00'
        param.createTime_end = this.queryParam.createTime_end + ' 23:59:59'
      }

      // delete param.createTimeRange; // 时间参数不传递后台
      return filterObj(param)
    },

    /**
     * 判断变量是否为空，
     * @param  {[type]}  param 变量
     * @return {Boolean}      为空返回true，否则返回false。
     */
    isEmpty(param) {
      if (param) {
        var param_type = typeof param
        if (param_type == 'object') {
          //要判断的是【对象】或【数组】或【null】等
          if (typeof param.length == 'undefined') {
            if (JSON.stringify(param) == '{}') {
              return true //空值，空对象
            }
          } else if (param.length == 0) {
            return true //空值，空数组
          }
        } else if (param_type == 'string') {
          //如果要过滤空格等字符
          var new_param = param.trim()
          if (new_param.length == 0) {
            //空值，例如:带有空格的字符串" "。
            return true
          }
        } else if (param_type == 'boolean') {
          if (!param) {
            return true
          }
        } else if (param_type == 'number') {
          if (!param) {
            return true
          }
        }
        return false //非空值
      } else {
        //空值,例如：
        //(1)null
        //(2)可能使用了js的内置的名称，例如：var name=[],这个打印类型是字符串类型。
        //(3)空字符串''、""。
        //(4)数字0、00等，如果可以只输入0，则需要另外判断。
        return true
      }
    },

    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //查询条件
      this.loading = true
      const that = this
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          if (res.result) {
            that.dataSource = res.result.records
            that.ipagination.total = res.result.total
          } else {
            that.dataSource = []
            that.ipagination.total = 0
          }
        }
        if (res.code === 510) {
          that.$message.warning(res.message)
        }
        that.loading = false
      })
    },

    batchDel: function () {
      if (!this.url.deleteBatch) {
        this.$message.error('请设置url.deleteBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectionRows.length; a++) {
          ids += this.selectionRows[a].invateuserdetailId + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: function () {
            deleteAction(that.url.deleteBatch, { ids: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          },
        })
      }
    },
    handleDelete: function (invateuserdetailId) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      deleteAction(that.url.delete, { id: invateuserdetailId }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },

    keyupEnter() {
      document.onkeydown = (e) => {
        let body = document.getElementsByTagName('body')[0]
        if (e.keyCode === 13) {
          this.loadData(1)
        }
      }
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
::v-deep .ant-table-thead > tr > th {
  font-weight: 600;
}
::v-deep .table-page-search-wrapper .ant-form-inline .ant-form-item .ant-form-item-control-wrapper {
  width: 62%;
}
::v-deep .ant-modal-title{
  font-weight: 600;
}
  .dataOrange{
    color:#ffa042;
  }
  .dataRed{
    color:#ff2c2c;
  }
</style>
